<template>
	<div class="visitor-detail">
        <nav-header>
			<template slot="menuBefore">
				<li><router-link to="/life/dormitory/visitor-record" tag="a">访客记录</router-link></li>
				<li class="gap">&gt;</li>
			</template>
			<li>访客详情</li>
		</nav-header>

        <div class="zh-tab" v-loading="loading.status" :element-loading-text="loading.txt">
			<div class="zh-tab-title">
                <span
                    v-if="itemDetail.picture_status == 1"
                    :class="activeapanel === 'image' ? 'is-active' : ''"
                    @click="changePanel('image')">
                    <i class="el-icon-picture"></i>图片</span>
				<span 
                    v-if="itemDetail.text_status == 1"
                    :class="activeapanel === 'table' ? 'is-active' : ''" 
                    @click="changePanel('table')">
                    <img :src="tableIcon">表格</span>
			</div>

			<div class="zh-t-list">
                <div v-show="activeapanel === 'image' ? true : false">
                    <div class="zh-list-title">
                        <p>{{itemDetail.name}}</p>
                        <p>{{getTime(itemDetail.start_time)}} 至 {{getTime(itemDetail.end_time)}}</p>
                    </div>

                    <div class="list-item">
                        <div class="item-img" v-for="(item, inx) in listImageData" :key="inx" v-loading="loading[`status${inx}`]" :element-loading-text="loading.txtimage">
                            <el-image  style="width: 100px; height: 100px" :src="BASE_URL + item.picture" fit="contain" lazy></el-image>
                            <div class="item-cover">
                                <i class="el-icon-close" @click="deleteImg(item, inx)"></i>
                                <span @click="checkImg(item)">查看</span>
                                <span class="repalace-input">
                                    <input type="file" accept="image/*" :class="`replace-uploader${inx}`" @change="replaceImg(item, inx)">
                                    <p @click="setFileReplace(item, inx)">重新上传</p>
                                </span>
                            </div>
                        </div>
                        <div class="item-img" v-loading="loading.statusupload" :element-loading-text="loading.txtimage">
                            <uploader 
                                ref="uploaderImg" 
                                class="uploader-broadcast" 
                                :autoStart="true"
                                :options="uploadOptionsImg"
                                :file-status-text="statusText" 
                                @file-added="fileAddImg"
                                @files-submitted="fileSubmit"
                                @file-removed="fileRemovedImg"
                                @file-success="fileSuccessImg"
                                @file-error="fileFailImg">
                                <uploader-unsupport></uploader-unsupport>
                                <uploader-btn :attrs="attrs"><i class="el-icon-plus"></i></uploader-btn>
                            </uploader>
                        </div>
                    </div>
                    
                    <div class="table-pagination" v-show="totalImgNumber > 13">
                        <el-pagination
                            @size-change="setCurrentImgSize"
                            @current-change="setCurrentImgPage"
                            :current-page="imgParam.pageIndex"
                            :page-sizes="[13, 26, 39, 52, 65, 104]"
                            :page-size="imgParam.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalImgNumber">
                        </el-pagination>
                    </div>
                </div>

                <div v-show="activeapanel === 'table' ? true : false">
                    <div class="zh-list-title">
                        <p>{{itemDetail.name}}</p>
                        <p>{{getTime(itemDetail.start_time)}} 至 {{getTime(itemDetail.end_time)}}</p>
                    </div>
                    <div class="zh-table">
                        <div class="zh-table-open clear">
                            <div class="zh-open-right fr">
                                <el-button type="primary" @click="newRecord('add')">添加</el-button>
                                <el-button type="primary" @click="batchImport">批量导入</el-button>
                                <el-button type="primary" @click="getAllData">批量导出</el-button>
                                <el-button type="danger" @click="deleteAllConfirm">批量删除</el-button>
                            </div>
                        </div>
                        <div class="zh-table-contents">
                            <el-table
                                :data="listTableData"
                                fixed
                                border
                                max-height="600"
                                @selection-change="tableSelectionChange"
                                style="width: 100%">
                                <el-table-column
                                    type="selection"
                                    width="50"
                                    align="center"
                                    fixed>
                                </el-table-column>
                                <el-table-column
                                    prop="respondents"
                                    label="姓名"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="start_time"
                                    label="来访时间"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="telphone"
                                    label="联系电话"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="id_number"
                                    label="身份证号"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="dormitory"
                                    label="拜访寝室"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="visitor"
                                    label="拜访人"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="cause"
                                    label="事由"
                                    align="center"
                                    show-overflow-tooltip>
                                    <template slot-scope="scope">
                                        {{scope.row.cause ? scope.row.cause : '-'}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="end_time"
                                    label="离开时间"
                                    align="center"
                                    show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    label="操作"
                                    align="center"
                                    :width="120">
                                    <template slot-scope="scope">
                                        <el-button @click="newRecord(scope.row)" type="text">编辑</el-button>
                                        <el-button @click="deleteConfirm(scope.row.id)" type="text" class="delete-button">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <div class="table-pagination" v-show="totalNumber > 10">
                                <el-pagination
                                    @size-change="setCurrentSize"
                                    @current-change="setCurrentPage"
                                    :current-page="listParam.pageIndex"
                                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                                    :page-size="listParam.pageSize"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="totalNumber">
                                </el-pagination>
                            </div>
                        </div>
                    </div>
                </div>
			</div>
		</div>

        <el-dialog 
            :title="recordTitle" 
            :visible.sync="recordVisible" 
            class="add-record-manage" 
            width="550px" 
            :before-close="cancelForm"
            :close-on-click-modal="false">
            <el-form :model="recordForm" :rules="rules" ref="recordForm" label-width="100px" class="demo-record-form">
                <el-form-item label="姓名：" prop="name">
                    <el-input v-model="recordForm.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="来访时间：" prop="visitingTime">
                    <el-date-picker
                        v-model="recordForm.visitingTime"
                        :picker-options="pickerOptions"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm"
                        value-format="yyyy-MM-dd HH:mm"
                        placeholder="请选择时间"
                        style="width:100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="离开时间：" prop="leaveTime">
                    <el-date-picker
                        v-model="recordForm.leaveTime"
                        :picker-options="pickerOptions"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm"
                        value-format="yyyy-MM-dd HH:mm"
                        placeholder="请选择时间"
                        style="width:100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="联系电话：" prop="phone">
                    <el-input v-model="recordForm.phone" placeholder="请输入联系电话" maxLength="11"></el-input>
                </el-form-item>
                <el-form-item label="身份证号：" prop="cardId">
                    <el-input v-model="recordForm.cardId" placeholder="请输入身份证号"></el-input>
                </el-form-item>
                <el-form-item label="拜访寝室：">
                    <el-input v-model="recordForm.room" placeholder="请输入拜访寝室"></el-input>
                </el-form-item>
                <el-form-item label="拜访人：" prop="people">
                    <el-input v-model="recordForm.people" placeholder="请输入拜访人"></el-input>
                </el-form-item>
                <el-form-item label="事由：">
                    <el-input
                        type="textarea"
                        placeholder="请输入事由"
                        :rows="3"
                        v-model="recordForm.reason"
                        maxlength="30"
                        show-word-limit>
                    </el-input>
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelForm" plain>取消</el-button>
                <el-button type="primary" @click="submitRecord('recordForm')">保存</el-button>
            </div>
        </el-dialog>

        <image-viewer
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
    </div>
</template>

<script>
import XLSX from 'xlsx';
import FileSaver from 'file-saver';
import {str2Buffer, uploaderFileFail} from './../../../tools/tool';
import tableIcon1 from './../../../../static/image/life/dormitory/table.png';
import tableIcon2 from './../../../../static/image/life/dormitory/table-active.png';

export default {
    data() {
        return {
            imagePreview: {
                showViewer: false,
                previewSrcList: []
            },
            recordVisible: false, // 是否弹窗
            imgVisible: false, // 图片预览
            isReplace: false, // 是否重新上传
            rowLen: 0, // 表格删除长度
            imgNumber: 0, // 上传图片的总数
            totalNumber: 0, // 表格总数
            totalImgNumber: 0, // 图片总数
            uploadRetryTimes: 100, //文件最大重传次数
            imgViewUrl: '', // 图片地址
            recordTitle: '添加', // 弹窗标题
            recordId: null, // 编辑id
            replaceId: null, // 被替换图片的id
            replaceInx: null,
            activeapanel: 'image', // 当前显示的页面
            tableIcon: tableIcon1, // 表格图片
            selected: [], // 表格选中数组
            listTableData: [], // 表格列表
            imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
            listImageData: [], // 图片列表
            itemDetail: {}, // 访客详情
            loading: {
                status: false,
                txt: '获取数据...',
                txtimage: '图片上传中...',
            },
            listParam: {
                pageIndex: 1, // 分页当前页数
                pageSize: 10 // 每页数据数量
            },
            imgParam: {
                pageIndex: 1, // 分页当前页数
                pageSize: 13 // 每页数据数量
            },
            recordForm: {
                name: '',
                visitingTime: '',
                leaveTime: '',
                phone: '',
                cardId: '',
                room: '',
                people: '',
                reason: ''
            },
            pickerOptions: {
                disabledDate: (time) => {
                    let startTime = new Date(this.itemDetail.start_time).getTime();
                    let endTiem = new Date(this.itemDetail.end_time).getTime();
                    // return time.getTime() < startTime || time.getTime() > endTiem  - 8.64e7
                    return time.getTime() < startTime || time.getTime() > endTiem;
                }
            },
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 1, message: '长度最少为 1 个字符', trigger: 'blur' }
                ],
                visitingTime: [
                    { required: true, validator: this.validatorStart, trigger: 'change' }
                ],
                leaveTime: [
                    { validator: this.validatorEnd, trigger: 'change' }
                ],
                phone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: this.rules.mobile.reg, message: this.rules.mobile.msg }
                ],
                cardId: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' },
                    { pattern: /(^\d{15}$)|(^\d{17}([0-9]|X)$)/, message: '身份证号格式错误' }
                ],
                people: [
                    { required: true, message: '请输入拜访人', trigger: 'blur' },
                    { min: 1, message: '长度最少为 1 个字符', trigger: 'blur' }
                ]
            },
            attrs: { accept: ["image/*"] },
            // uploadOptions: {
            //     target: this.BASE_URL + "/api/dormitory/dormitoryVisitorPicture",
            //     testChunks: false,
            //     headers: { Authorization: `Bearer ` + this.$g.access_token },
            //     query: {
            //         id: null,
            //         create_id: null,
            //         dormitory_visitor_id: null
            //     }
            // },
            uploadOptionsImg: {
                target: this.BASE_URL + "/api/video/thumbnail_upload",
                testChunks: false,
                headers: { 
                    Authorization: `Bearer ` + this.$g.access_token 
                }
            },
            statusText: {
                success: "上传成功",
                error: "上传出错",
                uploading: "正在上传...",
                paused: "暂停",
                waiting: "等待上传"
            },
        }
    },
    created() {
        this.getList();
    },
    computed: {
        getTime() {
            return (time) => {
                return time ? time.substr(0, 10) : '';
            }
        },
        imageIndex() {
            return this.imagePreview.previewSrcList.indexOf(this.imgViewUrl);
        }
    },
    methods: {
        /**
         * 获取详情信息
         */
        getList() {
            let success = (res => {
                this.itemDetail = res.data;

                if (this.itemDetail.picture_status == 1) {
                    this.activeapanel = 'image';
                    this.getImageList();
                } else {
                    this.activeapanel = 'table';
                }

                if (this.itemDetail.text_status == 1) {
                    this.getTableList();
                }
            })

            this.$ajax.get('api/dormitory/dormitoryVisitor',{params: {id: this.$route.params.id}, func:{success: success}})
        },
        /**
         * 获取图片详情
         */
        getImageList() {
            this.loading.status = true;

            let success = (res => {
                this.listImageData = [];
                this.loading.status = false;
                this.loading.txt = '获取数据';
                this.totalImgNumber = res.data.data_sum;

                this.$nextTick(() => {
                    this.listImageData = res.data.data;
                })
            })
            let params = {
                dormitory_visitor_id: this.$route.params.id,
                page_size: this.imgParam.pageSize,
                page_index: this.imgParam.pageIndex
            }

            this.$ajax.get('api/dormitory/dormitoryVisitorPicture',{params: params, func:{success: success}})
        },
        /**
         * 获取表格详情
         */
        getTableList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listTableData = res.data.data;
                this.totalNumber = res.data.data_sum;
            })
            let params = {
                dormitory_visitor_id: this.$route.params.id,
                page_size: this.listParam.pageSize,
                page_index: this.listParam.pageIndex
            }

            this.$ajax.get('api/dormitory/dormitoryVisitorDetail',{params: params, func:{success: success}})
        },
        /**
         * 切换页面
         * @param {String} pannel 页面标识
         */
        changePanel(panel) {
            this.activeapanel = panel;

            if (panel === 'table') {
                this.tableIcon = tableIcon2;
            } else {
                this.tableIcon = tableIcon1;
            }
        },
        /********************** 图片事件函数 **********************/
        /**
         * 删除图片
         * @param {String} item 图片信息
         * @param {Number} inx 图片在数组的下标
         */
        deleteImg(item, inx) {
            let success = (res => {
                this.$message.success(res.msg);

                if (this.listImageData.length - 1 === 0) {
                    if (this.imgParam.pageIndex > 1) {
                        this.imgParam.pageIndex-- ;
                    } else {
                        this.imgParam.pageIndex = 1;
                    }
                }

                this.getImageList();
            });
            let fail = (res =>{
                this.$message.error(res.msg);

                this.getImageList();
            }) 
            
            this.$ajax.delete('api/dormitory/dormitoryVisitorPicture',  {params: {id: item.id}, func: {success: success, fail: fail}})
        },
        /**
         * 查看图片
         * @param {String} item 图片信息
         */
        checkImg(item) {
            this.imgViewUrl = this.BASE_URL + item.picture;
            this.imagePreview.showViewer = true;
            this.imagePreview.previewSrcList = [this.BASE_URL + item.picture];
        },
        closeViewer() {
            this.imagePreview.showViewer = false;
        },
        /**
         * 隐藏 input 框，自动点击
         */
        setFileReplace(item, inx) {
            document.querySelector(`.replace-uploader${inx}`).click();
        },
        /**
         * 重新上传图片
         * 把原生input type=file标签获取到的文件添加到uploader插件
         * @param {String} item 图片信息
         * @param {Number} inx 图片在数组的下标
         */
        replaceImg(item, inx) {
            let imgFiles = document.querySelector(`.replace-uploader${inx}`).files;

            this.replaceId = item.id;
            this.replaceInx = inx;
            this.isReplace = true;
            this.$refs.uploaderImg.uploader.addFile(imgFiles[0]);
            this.$refs.uploaderImg.uploader.upload();
        },
        /**
         * 判断是否为重新上传
         */
        fileAdded() {
            if (this.isReplace) {
                this.$refs.uploaderImg.uploader.opts.target = this.BASE_URL + "/api/dormitory/editDormitoryVisitorPicture";
                this.uploadOptions.query.id = this.replaceId;
                this.uploadOptions.query.create_id = null;
                this.uploadOptions.query.dormitory_visitor_id = null;
            } else {
                this.uploadOptions.target = this.BASE_URL + "/api/dormitory/dormitoryVisitorPicture";
                this.$refs.uploaderImg.uploader.opts.target = this.BASE_URL + "/api/dormitory/dormitoryVisitorPicture";
                this.uploadOptions.query.id = null;
                this.uploadOptions.query.create_id = this.$g.user_id;
                this.uploadOptions.query.dormitory_visitor_id = this.$route.params.id;
            }
        },
        /**
         * 添加图片
         */
        fileAddImg(file, fileList) {},
        /**
         * 过滤文件格式
         */
        fileSubmit(files, fileList, event) {
            let domnode = document.querySelector(`.replace-uploader${this.replaceInx}`);

            for (let i=0; i<fileList.length; i++) {
                let file_type = fileList[i].fileType.toLocaleLowerCase();

                if(!this.imageType.includes(file_type)){
                    this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');
                    this.$refs.uploaderImg.uploader.removeFile(fileList[i]);
                    this.isReplace = false;
                    this.replaceInx = null;

                    domnode && (domnode.value = '');
                    return false;
                }

                if (fileList[i].size > 10240000) {
                    this.$message.warning("只允许上传10M以内的文件");
                    this.$refs.uploaderImg.uploader.removeFile(fileList[i]);
                    this.isReplace = false;
                    this.replaceInx = null;

                    domnode && (domnode.value = '');
                    return false;
                }

                this.imgNumber++;
            }

            if (domnode) {
                this.loading[`status${this.replaceInx}`] = true;
                this.replaceInx = null;
            } else {
                this.loading.statusupload = true;
            }

            this.$forceUpdate();
        },
        /**
         * 图片上传成功的事件
         */
        fileSuccessImg(rootFile, file, message, chunk) {
            var mess = eval("(" + message + ")");
            mess = handleResponseData( mess );
            
            if (parseInt(mess.data.status) === 1) {
                const success = (res => {
                    this.$refs.uploaderImg.uploader.removeFile(file);
                    this.loading = {
                        status: false,
                        txt: '获取数据...',
                        txtimage: '图片上传中...',
                    }
                    
                    this.listImageData = [];
                    this.getImageList();
                })
                const fail = (res => {})

                if (this.isReplace) {
                    let params = {
                        id: this.replaceId,
                        picture: mess.data.file_path,
                    }
                    this.$ajax.post("api/dormitory/editDormitoryVisitorPicture", params, {func: {success: success}});
                } else {
                    let params = {
                        dormitory_visitor_id: this.$route.params.id,
                        create_id: this.$g.user_id,
                        picture: mess.data.file_path,
                    }
                    this.$ajax.post("api/dormitory/dormitoryVisitorPicture", params, {func: {success: success}});
                }
            }

            this.isReplace = false;
        },
        /**
         * 上传图片失败
         */
        fileFail(rootFile, file, message, chunk) {
            this.isReplace = false;

            uploaderFileFail(this, this.$refs.uploaderImg.uploader, file, message);
        },
        fileFailImg(rootFile, file, message, chunk) {
            this.isReplace = false;

            uploaderFileFail(this, this.UploaderImg, file, message);
        },
        /**
         * 移除文件
         */
        fileRemoved(file) {
        },
        /**
         * 移除图片
         */
        fileRemovedImg(file) {},

        /********************** 表格事件函数 **********************/
        /**
         * 添加/编辑 记录
         * @param {String/Number} val 添加标识/记录 id
         */
        newRecord(val) {
            this.recordVisible = true;

            if (val === 'add') {
                this.recordId = null;
                this.recordTitle = '添加';
                this.recordForm = {
                    name: '',
                    visitingTime: '',
                    leaveTime: '',
                    phone: '',
                    cardId: '',
                    room: '',
                    people: '',
                    reason: ''
                }
            } else {
                this.recordId = val.id;
                this.recordTitle = '编辑';
                this.recordForm = {
                    name: val.respondents,
                    visitingTime: val.start_time,
                    leaveTime: val.end_time,
                    phone: val.telphone,
                    cardId: val.id_number,
                    room: val.dormitory,
                    people: val.visitor,
                    reason: val.cause
                }
            }

            this.$nextTick(() => {
                this.$refs.recordForm.clearValidate();
            })
        },
        /**
         * 保存添加/编辑信息
         * @param {String} formName 表单标识
         */
        submitRecord(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let params = {
                        id: this.recordId,
                        dormitory_visitor_id: this.$route.params.id,
                        respondents: this.recordForm.name,
                        visitor: this.recordForm.people,
                        start_time: this.recordForm.visitingTime,
                        end_time: this.recordForm.leaveTime,
                        telphone: this.recordForm.phone,
                        id_number: this.recordForm.cardId,
                        dormitory: this.recordForm.room,
                        cause: this.recordForm.reason,
                        create_id: this.recordId ? null : this.$g.user_id,
                    }

                    const success = (res => {
                        this.recordVisible = false;

                        this.getTableList();
                    })

                    if (this.recordId) {
                        this.$ajax.put("api/dormitory/dormitoryVisitorDetail", params, {func: {success: success}});
                    } else {
                        this.$ajax.post("api/dormitory/dormitoryVisitorDetail", params, {func: {success: success}});
                    }
                } else {
                    return false;
                }
            });
        },
        /**
         * 取消弹窗
         */
        cancelForm() {
            this.recordVisible = false;
        },
        /**
         * 确认批量删除
         */
        deleteAllConfirm() {
            if(this.selected.length === 0) {
                this.$message.warning("请选择要删除的项");
                return false;
            }

            let yes = (res => {
                let ids = [];
                this.rowLen = this.selected.length;

                this.selected.forEach(item => {
                    ids.push(item.id);
                })

                this.deleteList(ids);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt: '确定要删除这些项吗？'});
        },
        /**
         * 删除记录
         * @param {Number} id 记录 id
         */
        deleteConfirm(id) {
            let yes = (res => {
                this.rowLen = 1;
                this.deleteList(id);
            })
            let cancel = (res => {})

            this.e_confirm({yes: yes, cancel: cancel, txt: '确定要清空该记录吗？'});
        },
        /**
         * 删除数据
         * @param {String} id 删除的 id
         */
        deleteList(id) {
            this.loading.status = true;

            let success = (res => {
                this.$message.success(res.msg);
                
                if (this.listTableData.length - this.rowLen === 0) {
                    if (this.listParam.pageIndex > 1) {
                        this.listParam.pageIndex-- ;
                    } else {
                        this.listParam.pageIndex = 1;
                    }
                }

                this.getTableList();
            });
            let fail = (res =>{
                this.$message.error(res.msg);

                this.getTableList();
            }) 
            
            this.$ajax.delete('api/dormitory/dormitoryVisitorDetail', {params: {id}, func: {success: success, fail: fail}});
        },
        /**
         * 获取全部数据后导出
         */
        async getAllData() {
            if (this.totalNumber <= this.listParam.pageSize) {
                this.exportExcel(this.listTableData);
            } else {
                let All = [];
                let len = Math.ceil(this.totalNumber / 100);
                let success = (res=>{
                    All = [...All, ...res.data.data];
                })

                for (let i=1; i<=len; i++) {
                    let params = {
                        dormitory_visitor_id: this.$route.params.id,
                        page_index: i,
                        page_size: 100,
                    }

                    await this.$ajax.get('api/dormitory/dormitoryVisitorDetail', {params: params, func:{success: success}});
                }

                this.exportExcel(All);
            }
        },
        /**
         * 导出Excel表
         * @param {Array} allData 全部数据
         */
        exportExcel(allData) {       
            if(allData.length === 0){
                this.$message.warning("导出的数据为空！");
                return false;
            }
            
            let exportList = [];
            const defaultCellStyle =  { font: { name: "Verdana", sz: 14, color: "FF00FF88"}, fill: {fgColor: {rgb: "FFFFAA00"}}};
            const wopts = { bookType:'xlsx', bookSST:false, type:'binary', defaultCellStyle: defaultCellStyle, showGridLines: false};
            const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };

            for (let i = 0; i <= allData.length - 1;  i++) {
                if(i===0){
                    this.live_name  =  allData[i].l_name
                }

                exportList.push({
                    "姓名": allData[i].respondents,
                    "来访时间": allData[i].start_time,
                    "联系电话": allData[i].telphone,
                    "身份证号": allData[i].id_number,
                    "拜访寝室": allData[i].dormitory,
                    "拜访人": allData[i].visitor,
                    "事由": allData[i].cause,
                    "离开时间": allData[i].end_time
                });
            }

            wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(exportList)
            wb.Sheets['Sheet1']["!cols"] = [{
                wpx: 140
            }, {
                wpx: 140
            }, {
                wpx: 140
            }, {
                wpx: 100
            }, {
                wpx: 180
            }, {
                wpx: 80
            }, {
                wpx: 100
            }, {
                wpx: 250
            }, {
                wpx: 140
            }];

            //创建二进制对象写入转换好的字节流
            let tmpDown =  new Blob([str2Buffer(XLSX.write(wb, wopts))], { type: "application/octet-stream" });
            FileSaver.saveAs(tmpDown, `访客记录-文字详情.xlsx`);
        },
        /**
         * 列表数据多选
         * @param {Array} val 选中数据的数组
         */
        tableSelectionChange(val) {
            this.selected = val;
        },
        /**
         * 设置列表每页数据数量
         */
        setCurrentSize(val) {
            this.listParam.pageIndex = 1;
            this.listParam.pageSize = val;

            this.getTableList();
        },
        /**
         * 设置列表的当前页数
         * @param {Number} val 页数
         */
        setCurrentPage(val) {
            this.listParam.pageIndex = val;

            this.getTableList();
        },
        /**
         * 设置列表每页数据数量
         */
        setCurrentImgSize(val) {
            this.imgParam.pageIndex = 1;
            this.imgParam.pageSize = val;

            this.getImageList();
        },
        /**
         * 设置列表的当前页数
         * @param {Number} val 页数
         */
        setCurrentImgPage(val) {
            this.imgParam.pageIndex = val;

            this.getImageList();
        },
         /**
         * 跳到批量导入页面
         */
        batchImport(){
            this.$router.push("/life/dormitory/visitor-batch-import/" + this.$route.params.id)
        },
        /**
         * 验证开始时间规则
         */
        validatorStart(rule, value, callback) {
            if (value === '') {
                callback(new Error('请选择来访时间'));
            } else {
                if (this.recordForm.leaveTime && +new Date(this.recordForm.visitingTime) >= +new Date(this.recordForm.leaveTime)) {
                    callback(new Error('来访时间不能大于离开时间'));
                } else {
                    callback();
                }
            }
        },
        /**
         * 验证结束时间规则
         */
        validatorEnd(rule, value, callback) {
            if (this.recordForm.visitingTime && +new Date(this.recordForm.visitingTime) >= +new Date(this.recordForm.leaveTime)) {
                callback(new Error('离开时间不能小于来访时间'));
            } else {
                callback();
            }
        },
    },
}
</script>

<style lang="scss">
.visitor-detail {
    .el-image {
        width: 100% !important;
        height: 100% !important;
    }

    .list-item {
        display: flex;
        flex-wrap: wrap;
        margin: 50px 0;

        .item-img {
            position: relative;
            margin-right: 20px;
            margin-bottom: 20px;
            width: 200px;
            height: 200px;
            text-align: center;
            border: 1px solid #CFE9FF;
            box-sizing: border-box;

            .uploader-broadcast {
                height: 100%;
            }

            .uploader-btn {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 100%;
                background: #F4F9FF;
                border: 1px dashed #7A9BB6;
                box-sizing: border-box;

                i {
                    font-size: 72px;
                    color: #81B1E1;
                }
            }

            img {
                width: 100%;
                height: 100%;
                object-fit: contain;
            }

            .item-cover {
                display: none;
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);

                i,
                span {
                    position: absolute;
                    color: #fff;
                    cursor: pointer;
                }

                i {
                    top: 5px;
                    right: 5px;
                    font-size: 18px;
                }

                i:hover {
                    animation: imgClose 0.5s forwards linear;
                }

                @keyframes imgClose {
                    0% {
                        color: #fff;
                    }
                    100% {
                        color: red;
                    }
                }

                span {
                    top: 56px;
                    left: 66px;
                    width: 79px;
                    height: 36px;
                    line-height: 36px;
                    background: #348EFC;
                    border-radius: 4px;
                }

                .repalace-input {
                    top: 109px;
                    background: #E18330;
                    overflow: hidden;

                    input {
                        width: 79px;
                        height: 36px;
                        line-height: 36px;
                        vertical-align: top;
                        opacity: 0;
                    }

                    p {
                        position: absolute;
                        top: 0;
                        left: 0;
                        display: inline-block;
                        margin: 0;
                        padding: 0;
                        text-align: center;
                        width: 100%;
                    }
                }
            }
        }

        .item-img:last-child {
            border: 1px solid transparent;
        }

        .item-img:hover {
            .item-cover {
                display: block;
            }
        }
    }
    
    .zh-tab-title {
        margin-bottom: 33px;
        font-size: 0;

        span {
            display: inline-block;
            width: 90px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            font-size: 14px;
            color: #666666;
            border: 1px solid #DDD;
            box-sizing: border-box;
            cursor: pointer;

            i,
            img {
                margin-right: 4px;
                font-size: 18px;
                vertical-align: middle;
            }
        }

        span:first-child {
            border-top-left-radius: 4px;
            border-bottom-left-radius: 4px;
        }

        span:last-child {
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
        }

        .is-active {
            color: #fff;
            background: #348EFC;
            border: 1px solid #348EFC;
        }
    }

    .zh-list-title {
        >p:first-child {
            font-size: 20px;
            font-weight: bold;
        }

        >p:last-child {
            margin: 0;
            font-size: 12px;
            color: #666;
        }
    }
}
</style>